package com.hotel.user.controller;

import com.hotel.common.entity.User;
import com.hotel.common.entity.Permission;
import com.hotel.common.utils.Result;
import com.hotel.user.service.UserService;
import com.hotel.user.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.HashMap;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private com.hotel.user.feign.AuthClient authClient;

    @Autowired
    private PermissionService permissionService;

    @PostMapping(value = "/login", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Result<String> login(@RequestBody Map<String, String> body) {
        String username = body.get("username");
        String password = body.get("password");
        Result<User> userResult = userService.getUserByUsername(username);
        if (!userResult.isSuccess() || userResult.getData() == null) {
            return Result.error("用户名或密码错误");
        }
        User user = userResult.getData();
        if (user.getPasswordBcrypt() == null || !BCrypt.checkpw(password, user.getPasswordBcrypt())) {
            return Result.error("用户名或密码错误");
        }

        // 拉取权限并向auth-service请求生成单token
        Result<List<Permission>> permsResult = permissionService.getPermissionsByUserId(user.getId());
        java.util.List<String> codes = permsResult.isSuccess() && permsResult.getData() != null ?
                permsResult.getData().stream().map(Permission::getPermissionCode).toList() : java.util.Collections.emptyList();

        java.util.Map<String, Object> payload = new java.util.HashMap<>();
        payload.put("userId", user.getId());
        payload.put("permissions", codes);
        Result<String> tokenResp = authClient.generate(payload);
        if (tokenResp == null || !tokenResp.isSuccess() || tokenResp.getData() == null) {
            return Result.error("令牌生成失败");
        }
        return Result.success(tokenResp.getData());
    }
    

    @PostMapping("/register")
    public Result<Long> register(@RequestBody Map<String, Object> body) {
        User user = new User();
        user.setUsername((String) body.get("username"));
        // 前端传 password，后端用 passwordBcrypt 字段承载明文并在服务层加密
        user.setPasswordBcrypt((String) body.get("password"));
        user.setTel((String) body.get("phone"));
        user.setRealName((String) body.getOrDefault("realName", ""));
        return userService.register(user);
    }

    @PostMapping("/logout")
    public Result<Void> logout(@RequestHeader("Authorization") String authorization) {
        if (authorization != null && authorization.startsWith("Bearer ")) {
            String token = authorization.substring(7);
            redisTemplate.delete("token:" + token);
        }
        return Result.success();
    }

    @GetMapping("/me")
    public Result<User> getCurrentUser(@RequestHeader("X-User-Id") Long userId) {
        return userService.getUserById(userId);
    }

    @GetMapping("/info")
    public Result<Map<String, Object>> info(@RequestHeader(value = "X-User-Id", required = false) String userIdHeader) {
        if (userIdHeader == null || userIdHeader.isEmpty()) {
            return Result.error("未登录");
        }
        Long userId = Long.valueOf(userIdHeader);
        Result<User> userResult = userService.getUserById(userId);
        if (!userResult.isSuccess() || userResult.getData() == null) {
            return Result.error("用户不存在");
        }
        Result<List<Permission>> permsResult = permissionService.getPermissionsByUserId(userId);
        List<String> permissionCodes = permsResult.isSuccess() && permsResult.getData() != null
                ? permsResult.getData().stream().map(Permission::getPermissionCode).collect(Collectors.toList())
                : java.util.Collections.emptyList();

        Map<String, Object> data = new HashMap<>();
        data.put("user", userResult.getData());
        data.put("permissions", permissionCodes);
        return Result.success(data);
    }

    @PutMapping("/profile")
    public Result<Void> updateProfile(@RequestHeader(value = "X-User-Id", required = false) String userIdHeader,
                                      @RequestBody Map<String, Object> body) {
        if (userIdHeader == null || userIdHeader.isEmpty()) {
            return Result.error("未登录");
        }
        Long userId = Long.valueOf(userIdHeader);
        User user = new User();
        user.setId(userId);
        if (body.get("realName") != null) {
            user.setRealName(String.valueOf(body.get("realName")));
        }
        if (body.get("tel") != null) {
            user.setTel(String.valueOf(body.get("tel")));
        }
        userService.updateUser(user);
        return Result.success();
    }
}